package com.ssyc.student.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;

import com.ssyc.common.base.LazyBaseFragment;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.MyListView;
import com.ssyc.student.R;
import com.ssyc.student.activity.StudentPrepareDetectionActivity;
import com.ssyc.student.activity.StudentShowPrepareDetectionAnswerActivity;
import com.ssyc.student.adapter.StPrepareLvAdapter;
import com.ssyc.student.adapter.StShowAnswerLvAdapter;
import com.ssyc.student.bean.PrepareDetectionInfo;
import com.ssyc.student.bean.StAnswerInfo;
import com.ssyc.student.bean.StShowAnserInfo;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 学生端--预习检测--选择答案的Fragment
 * Created by Administrator on 2018/5/25 0025.
 */

public class StudentChooseAnserDetectionFramgent extends LazyBaseFragment {

    //接受的Question对象
    private PrepareDetectionInfo.DataBean.QuestionListBean question;

    //展示供选择答案的列表
    private MyListView answerLv;
    //展示选择答案选项的适配器
    private StPrepareLvAdapter adapter;
    //页面组装的选择答案的数据集合
    private List<StAnswerInfo> answerInfos;


    //展示选择后的答案和正确答案的列表
    private MyListView showAnswerLv;
    //用于展示选择后的答案和正确答案的列表数据
    private List<StShowAnserInfo> chooseAnswerInfos;
    //展示选择答案的列表适配器
    private StShowAnswerLvAdapter showAnswerAdapter;

    //传递选择答案的事件标识
    public static final String CHOOSEANSWER = "chooseanswer";

    //服务器返回的供选择的答案的集合
    private List<String> choose_answers;

    //服务器返回的每项的正确答案的集合
    private String[] rightAnswers;


    //A到Z的数据集合
    private String[] chartNums;


    //查看答案展示答案列表项是否可以点击的表示,默认为true收到查看答案的标识为false
    private boolean isItemClicked = true;


    //翻页的标识
    public static final int VPSCROLL = 0x210;


    public static StudentChooseAnserDetectionFramgent newInstance(PrepareDetectionInfo.DataBean.QuestionListBean question) {
        StudentChooseAnserDetectionFramgent studentChooseAnserDetectionFramgent = new StudentChooseAnserDetectionFramgent();
        Bundle bundle = new Bundle();
        bundle.putSerializable(CHOOSEANSWER, question);
        studentChooseAnserDetectionFramgent.setArguments(bundle);
        return studentChooseAnserDetectionFramgent;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_student_choose_answer_detection;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

        showContent();

        //初始化视图
        initView(view);

        //获取页面JSON
        getAnswerJson();

        //显示答案
        initAnswerLv();

        //设置展示选择答案的列表
        initShowAnserLv();
    }

    /**
     * 获取传递过来的页面选择答案的json数据
     *
     * @return
     */
    public void getAnswerJson() {

        //初始化提供答案的集合
        answerInfos = new ArrayList<>();

        //展示已经选择的答案数据,需要根据传递过来的数据进行数据组装
        chooseAnswerInfos = new ArrayList<>();

        question = (PrepareDetectionInfo.DataBean.QuestionListBean) getArguments().getSerializable(CHOOSEANSWER);

        //获取选择的答案选项
        choose_answers = new ArrayList<>();

        List<PrepareDetectionInfo.DataBean.QuestionListBean.JpglistBean> jpglist = question.getJpglist();
        if (null != jpglist && jpglist.size() != 0) {
            for (int i = 0; i < jpglist.size(); i++) {
                choose_answers.add(jpglist.get(i).getText());
            }
        }

        //获取正确答案选项的字符串,这里需要用￠符号切割
        String rightAnswer = question.getWordpic();

        if (!TextUtils.isEmpty(rightAnswer)) {
            rightAnswers = rightAnswer.split("￠");
        }

        //初始化展示答案选项的集合
        for (int i = 0; i < choose_answers.size(); i++) {

            //初始化选择答案的数据
            StAnswerInfo info = new StAnswerInfo();

            //默认都是没有选择的
            info.setSelect(false);

            //设置选项的答案
            info.setAnswerContent(choose_answers.get(i));

            //设置标号
            info.setAnswerNum(chartNums[i]);

            answerInfos.add(info);

        }

        //初始化自己选择答案的集合
        if (null != rightAnswers && rightAnswers.length != 0) {
            for (int i = 0; i < rightAnswers.length; i++) {

                //初始化展示选择答案的数据
                StShowAnserInfo showAnserInfo = new StShowAnserInfo();

                //计算正确答案的索引位置,计算规则,通过服务器返回的rightAnswers中的每一项的值在choose_answers的位置来确定
                showAnserInfo.setRightNum(getRightNum(i));

                //设置序号
                showAnserInfo.setId((i + 1) + "");

                //初始化的时候设置选择的答案序列号为空串
                showAnserInfo.setChooseNum("");

                chooseAnswerInfos.add(showAnserInfo);
            }
        }
    }

    /**
     * 初始化视图
     *
     * @param view
     */
    private void initView(View view) {

        //获取A到Z的字母数组
        chartNums = getResources().getStringArray(R.array.base_letters);

        //展示提供选择答案的列表
        answerLv = view.findViewById(R.id.lv_choose_answer);

        //展示已经选择后答案的列表
        showAnswerLv = view.findViewById(R.id.lv_show_answer);

        //初次进入的时候隐藏自己选择的答案列表
        showAnswerLv.setVisibility(View.GONE);
    }

    /**
     * 根据服务器返回的每一项的正确答案来确定正确答案在服务器返回的选择答案选项中的位置，根据位置来确定索引ABCDEFGH
     *
     * @param pos
     */
    private String getRightNum(int pos) {
        int index = -1;
        for (int i = 0; i < choose_answers.size(); i++) {
            //去除空格后进行比较
            if (rightAnswers[pos].replaceAll(" ", "").equals(choose_answers.get(i).replace(" ", ""))) {
                index = i;
                break;
            }
        }

        //根绝返回的位置来确定正确答案的索引
        return chartNums[index];
    }

    /**
     * 提供展示选择答案的ListView
     */
    private void initAnswerLv() {
        adapter = new StPrepareLvAdapter(getContext(), answerInfos, R.layout.student_lv_prepare_answer);
        answerLv.setAdapter(adapter);
        //选择答案后的操作
        answerLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
                //条目的点击事件
                if (isItemClicked) {
                    //条目可点击
                    //第一步:对选择的位置进行取反操作
                    if (answerInfos.get(pos).isSelect) {
                        //已经被被选择了,提示该答案已经被选择
                        UiUtils.Toast("该答案已经被选择", false);
                        return;
                    } else {

                        //如果填空已经被选择完毕,这不让选择
                        if (hasComplete()) {
                            UiUtils.Toast("已经作答完毕", false);
                        } else {
                            answerInfos.get(pos).isSelect = true;
                            adapter.notifyDataSetChanged();

                            //通知宿主Activity界面进行更新显示
                            BusInfo busInfo = new BusInfo();
                            busInfo.setType(4);
                            busInfo.setPos(pos);
                            busInfo.setChooseAnswer(answerInfos.get(pos).answerContent);
                            EventBus.getDefault().post(busInfo);

                            //通知展示用户选择答案的适配器进行刷新
                            Map<Integer, String> underLineMap = StudentPrepareDetectionActivity.getUnderLineMap();
                            for (int i = 0; i < chooseAnswerInfos.size(); i++) {
                                if ((!TextUtils.isEmpty(underLineMap.get(i))) && (!StudentPrepareDetectionActivity.regStr.equals(underLineMap.get(i)))) {
                                    chooseAnswerInfos.get(i).setChooseNum(underLineMap.get(i).trim());
                                } else {
                                    chooseAnswerInfos.get(i).setChooseNum("");
                                }
                            }
                            showAnswerAdapter.notifyDataSetChanged();

                            //判断是否作答完毕,作答完毕后通知VP翻页到提交界面
                            if (hasComplete()) {
                                //通知StudentPrepareDetectionActivity切换到提交界面
                                BusInfo info = new BusInfo();
                                info.setType(VPSCROLL);
                                EventBus.getDefault().post(info);
                            }

                        }
                    }

                } else {
                    //条目不可点击
                    UiUtils.Toast("查看答案模式下不可选择", false);
                    return;
                }

            }
        });
    }

    /**
     * 是否作答完毕的方法
     * 返回值true表示作答完毕,false表示没有作答完毕
     *
     * @return
     */
    private boolean hasComplete() {
        boolean res = true;
        Map<Integer, String> underLineMap = StudentPrepareDetectionActivity.getUnderLineMap();
        //如果map的所有key对应的值都不为""或者5个下划线,证明作答完毕
        for (int i = 0; i < underLineMap.size(); i++) {
            if (TextUtils.isEmpty(underLineMap.get(i)) || StudentPrepareDetectionActivity.regStr.equals(underLineMap.get(i))) {
                res = false;
                break;
            }
        }

        return res;

    }

    /**
     * 设置展示选择答案的列表
     */
    private void initShowAnserLv() {
        showAnswerAdapter = new StShowAnswerLvAdapter(getContext(), chooseAnswerInfos, R.layout.student_lv_show_answer);
        showAnswerLv.setAdapter(showAnswerAdapter);
    }

    /**
     * 根据选择的答案的位置来更新用户选择答案的序号的方法
     *
     * @param pos
     */
    private void setChooseAnswerNum(int pos) {
        if (null != chooseAnswerInfos) {
            chooseAnswerInfos.get(pos).setChooseNum(chartNums[pos]);
        }
    }


    /**
     * 处理Activity发送过来的通知选项答案重置状态的事件
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo) {

            if (StudentPrepareDetectionActivity.UPDATETYPE == busInfo.getType()) {

                //收到Activity界面点击填空位置答案消失的更新事件,需要同时更新选择答案的列表条目状态和展示答案的列表条目状态
                int pos = busInfo.getPos();

                Map<Integer, String> underLineMap = StudentPrepareDetectionActivity.getUnderLineMap();

                for (int i = 0; i < answerInfos.size(); i++) {
                    if ((!"".equals(underLineMap.get(pos))) && (!StudentPrepareDetectionActivity.regStr.equals(underLineMap.get(pos)))) {
                        //接受消息的一瞬间underLineMap对应的位置有ABCDEF...的标号的
                        if (answerInfos.get(i).getAnswerNum().equals(underLineMap.get(pos).trim())) {
                            answerInfos.get(i).isSelect = false;
                        }
                    }
                }
                adapter.notifyDataSetChanged();

                //更新展示选择答案位置的选择的答案选项
                chooseAnswerInfos.get(pos).setChooseNum("");
                showAnswerAdapter.notifyDataSetChanged();
            } else if (StudentShowPrepareDetectionAnswerActivity.LOOKANSWER == busInfo.getType()) {
                //收到查看答案的消息
                //显示展示选择答案的列表
                showAnswerLv.setVisibility(View.VISIBLE);
                //同时设置答案选项的列表为不可交互
                answerLv.setEnabled(false);
                isItemClicked = false;
            }
        }
    }
}
